/**
 * TTS语音合成服务 - 精简版
 * 支持降级策略：后端API -> Web Speech API -> 直接播放
 * 支持音色切换功能
 */
import { requestManager, generateId } from '../utils/index.js'

class TTSService {
  constructor() {
    this.cache = new Map()
    this.currentVoice = 'xiaoyan' // 默认音色
    this.voices = [] // 音色列表
    this.loadVoices()
  }

  /**
   * 加载音色列表
   */
  async loadVoices() {
    try {
      const response = await fetch('/api/tts/voices')
      if (response.ok) {
        const result = await response.json()
        this.voices = result.data || []
        console.log('🎵 音色列表加载成功:', this.voices.length, '个音色')
      }
    } catch (error) {
      console.warn('加载音色列表失败:', error.message)
      // 使用默认音色列表
      this.voices = [
        { id: 'xiaoyan', name: '小燕', gender: '女', description: '青年女声，甜美自然' },
        { id: 'xiaoyu', name: '小宇', gender: '男', description: '青年男声，稳重成熟' }
      ]
    }
  }

  /**
   * 获取音色列表
   * @returns {Array} 音色列表
   */
  getVoices() {
    return this.voices
  }

  /**
   * 设置当前音色
   * @param {string} voiceId - 音色ID
   */
  setVoice(voiceId) {
    // 如果音色列表还没加载完成，先设置音色，稍后验证
    if (this.voices.length === 0 || this.voices.find(v => v.id === voiceId)) {
      this.currentVoice = voiceId
      console.log('🎵 音色已切换为:', voiceId)
      // 清空缓存，因为音色变了
      this.clearCache()
    } else {
      console.warn('不支持的音色:', voiceId, '可用音色:', this.voices.map(v => v.id))
    }
  }

  /**
   * 获取当前音色
   * @returns {string} 当前音色ID
   */
  getCurrentVoice() {
    return this.currentVoice
  }

  /**
   * 生成TTS音频 - 主要入口方法（带降级策略）
   * @param {string} text - 待转换的文本
   * @param {string} messageId - 消息ID
   * @param {string} voice - 音色ID（可选，默认使用当前音色）
   * @returns {Promise<string>} 音频URL或特殊标识
   */
  async generateAudio(text, messageId, voice = null) {
    if (!text || typeof text !== 'string') {
      throw new Error('Invalid text input')
    }
    
    const targetVoice = voice || this.currentVoice
    const cacheKey = `${text}_${targetVoice}`
    
    // 检查缓存
    if (this.cache.has(cacheKey)) {
      console.log('🎯 TTS缓存命中:', text.substring(0, 20) + '...', '音色:', targetVoice)
      return this.cache.get(cacheKey)
    }
    
    // 尝试降级策略：后端API -> Web Speech API -> 直接播放
    try {
      return await this.generateWithBackendAPI(text, messageId, targetVoice)
    } catch (error) {
      console.warn('后端TTS API失败，降级到Web Speech API:', error.message)
      
      try {
        return await this.generateWithWebSpeechAPI(text, messageId)
      } catch (error2) {
        console.warn('Web Speech API失败，使用直接播放:', error2.message)
        return `direct-playback:${messageId}`
      }
    }
  }

  /**
   * 后端TTS API
   */
  async generateWithBackendAPI(text, messageId, voice) {
    console.log('🎵 调用后端TTS API:', { text: text.substring(0, 20) + '...', voice, messageId })
    
    const response = await fetch('/api/tts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text, voice })
    })

    if (!response.ok) {
      const errorText = await response.text()
      console.error('后端TTS API错误:', response.status, errorText)
      throw new Error(`Backend API error: ${response.status}`)
    }

    const audioBlob = await response.blob()
    const audioUrl = URL.createObjectURL(audioBlob)
    const cacheKey = `${text}_${voice}`
    this.cache.set(cacheKey, audioUrl)
    console.log('🎵 后端TTS API成功:', { voice, audioSize: audioBlob.size })
    return audioUrl
  }

  /**
   * Web Speech API
   */
  async generateWithWebSpeechAPI(text, messageId) {
    if (!('speechSynthesis' in window)) {
      throw new Error('Web Speech API not supported')
    }

    return new Promise((resolve, reject) => {
      const utterance = new SpeechSynthesisUtterance(text)
      utterance.lang = 'zh-CN'
      utterance.rate = 0.9
      utterance.pitch = 1.0
      utterance.volume = 1.0

      utterance.onend = () => resolve(`web-speech-api:${messageId}`)
      utterance.onerror = (error) => reject(new Error(`Web Speech API error: ${error.error}`))
      
      window.speechSynthesis.speak(utterance)
    })
  }

  /**
   * 清空缓存
   */
  clearCache() {
    for (const [cacheKey, audioUrl] of this.cache) {
      if (audioUrl.startsWith('blob:')) {
        URL.revokeObjectURL(audioUrl)
      }
    }
    this.cache.clear()
    console.log('🗑️ TTS缓存已清空')
  }

  /**
   * 取消所有请求
   */
  cancelAllRequests() {
    // 停止Web Speech API
    if ('speechSynthesis' in window) {
      window.speechSynthesis.cancel()
    }
  }
}

// 创建单例实例
const ttsService = new TTSService()

export default ttsService